/*
 * XXX
 */

package edu.uhcl.csci4838.group3.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorHoliday;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorSemester;
import edu.uhcl.csci4838.group3.database.info.Holiday;
import edu.uhcl.csci4838.group3.database.info.Semester;
import edu.uhcl.csci4838.group3.view.help.HelpActivity;

/**
 * XXX
 * 
 * @author Chris Waguespack
 */
public class SemesterActivity extends Activity {
	
	/**
	 * XXX
	 * 
	 * @author Chris Waguespack
	 *
	 */
	private static class HolidayViewBinder implements
			SimpleCursorAdapter.ViewBinder {
		
		/**
		 * XXX
		 * 
		 */
		public HolidayViewBinder() {
			// TODO Auto-generated constructor stub
		}

		/**
		 * XXX
		 * 
		 * @param view XXX
		 * @param cursor XXX
		 * @param columnIndex XXX
		 * @return XXX
		 */
		/* 
		 * (non-Javadoc)
		 * 
		 * @see android.widget.SimpleCursorAdapter.ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)
		 */
		@Override
		public boolean setViewValue(final View view,
				final Cursor cursor,
				final int columnIndex) {
			switch (view.getId()) {
				case R.id.tv_startDate:
					final long startDate = ((CursorHoliday) cursor).getColStartDate();
					((TextView) view).setText(DateFormat.format("MM/dd/yy",
							startDate));
					return true;
				case R.id.tv_endDate:
					final long endDate = ((CursorHoliday) cursor).getColEndDate();
					((TextView) view).setText(DateFormat.format("MM/dd/yy",
							endDate));
					return true;
				default:
					return false;
			}
		}
		
	}
	
	/**
	 * The database helper object.
	 */
	private static BackpackEduDatabaseHelper dbHelper;
	
	/**
	 * The semester cursor used to populate this view.
	 */
	private CursorSemester semesterCursor;
	
	private static TextView tvSemesterName;
	private static ListView lvHolidays;
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		this.getMenuInflater()
				.inflate(R.menu.options_semester,
						menu);
		return true;
	}
	
	/**
	 * XXX
	 * 
	 * @param item
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_item_edit_semester:
				this.startActivity(new Intent(this.getApplicationContext(),
						EditSemesterActivity.class).putExtra(this.getString(R.string.intent_extra_semesterId),
						this.semesterCursor.getColId()));
				return true;
			case R.id.menu_item_delete_semester:
				this.showDeleteSemesterDialog();
				return true;
			case R.id.menu_item_settings:
				this.startActivity(new Intent(this.getApplicationContext(),
						SettingsActivity.class));
				return true;
			case R.id.menu_item_about:
				 this.startActivity(new Intent(getApplicationContext(),
						 AboutActivity.class));
				return true;
			case R.id.menu_item_help:
				this.startActivity(new Intent(this.getApplicationContext(),
						HelpActivity.class));
				return true;
			default:
				Log.wtf("BackpackEDU",
						"Undefined options menu item.");
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param savedInstanceState
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ActivityGroup#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.activity_view_semester);
		
		// Get components
		SemesterActivity.tvSemesterName = (TextView) this.findViewById(R.id.textView_showSemesterName);
		SemesterActivity.lvHolidays = (ListView) this.findViewById(R.id.lv_holidays);
		
		// Calling intent
		final Intent callingIntent = this.getIntent();
		final long semesterId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_semesterId),
				-1);
		
		// Start the database helper
		SemesterActivity.dbHelper = new BackpackEduDatabaseHelper(this);
		
		// Cursor
		ContentValues criteria = new ContentValues();
		criteria.put(Semester.ID,
				Long.valueOf(semesterId));
		this.semesterCursor = SemesterActivity.dbHelper.getSemester(criteria,
				null,
				true);
		this.startManagingCursor(this.semesterCursor);
		
		// Populate the fields
		SemesterActivity.tvSemesterName.setText(this.semesterCursor.getColName());
		
		// Holidays
		criteria = new ContentValues();
		criteria.put(Holiday.SEMESTER_ID,
				Long.valueOf(semesterId));
		final CursorHoliday holidayCursor = SemesterActivity.dbHelper.getHoliday(criteria,
				new String[] { Holiday.START_DATE, Holiday.END_DATE },
				true);
		this.startManagingCursor(holidayCursor);
		if (holidayCursor.getCount() < 1) {
			this.findViewById(R.id.textView_holidays).setVisibility(View.GONE);
			SemesterActivity.lvHolidays.setVisibility(View.GONE);
		} else {
			// Set up the adapter
			final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.item_holiday,
					holidayCursor,
					new String[] {
							Holiday.NAME,
							Holiday.START_DATE,
							Holiday.END_DATE },
					new int[] {
							R.id.tv_holidayName,
							R.id.tv_startDate,
							R.id.tv_endDate });
			adapter.setViewBinder(new HolidayViewBinder());
			SemesterActivity.lvHolidays.setAdapter(adapter);
		}
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		SemesterActivity.dbHelper.close();
		super.onDestroy();
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		super.onRestart();
		// TODO Q&D fix to get it working
		this.semesterCursor.moveToFirst();
	}
	
	/**
	 * XXX
	 */
	private void showDeleteSemesterDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.menu_title_delete_semester)
				.setMessage("Are you sure you want to delete the semester \""
						+ this.semesterCursor.getColName()
						+ "\" and all of its associated classes?")
				.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								SemesterActivity.dbHelper.deleteSemester(SemesterActivity.this.semesterCursor.getColId());
								SemesterActivity.this.finish();
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	// TODO !!! if you go semester->edit semester->delete semester, that brings
	// you back to the deleted semester, so maybe do it for an intent return and
	// if the return is "delete", finish() the view semester activity
	// TODO view->edit(for result)->(back)->update
	

//public class CheckStartActivityForResult extends Activity {
//     int requestCode;
//    /** Called when the activity is first created. */
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        Log.d("CheckStartActivity","OnCreate");
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
//        Intent i = new Intent(this,CalledActivity.class);      
//        startActivityForResult(i, requestCode);
//    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
//        // TODO Auto-generated method stub
//        super.onActivityResult(requestCode, resultCode, data);
//        if(resultCode==1){
//            Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
//        }
//        else{
//            Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
//        }
//    }
//}
//
//
//
//setResult(RESULT_OK, new Intent()); finish();
}
